package com.lishu.carsafe.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.lishu.carsafe.R;
import com.lishu.carsafe.constant.UserPreferences;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.listener.UploadFileListener;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.FaultDetailModel;
import com.lishu.carsafe.model.FaultToAddModel;
import com.lishu.carsafe.model.entity.Creator;
import com.lishu.carsafe.model.entity.Fault;
import com.lishu.carsafe.model.entity.Level;
import com.lishu.carsafe.model.entity.Type;
import com.lishu.carsafe.model.entity.VehicleId;
import com.lishu.carsafe.utils.BitmapUtil;
import com.lishu.carsafe.utils.ImageUtil;
import com.lishu.carsafe.utils.ListUtil;
import com.lishu.carsafe.utils.NetUtil;
import com.lishu.carsafe.utils.TimeUtil;
import com.lishu.carsafe.utils.ToastUtil;

import java.util.List;

public class FaultDetailActivity extends FaultEditBaseActivity implements View.OnClickListener{
    private String faultId;
    private FaultDetailModel.FaultDetail mFaultDetail;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    String path2 = (String) msg.obj;
                    Bitmap bitmap2 = BitmapUtil.getNetVideoBitmap(path2);
                    upload_1.setImageBitmap(bitmap2);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fault_add);
        faultId = getIntent().getStringExtra("faultId");

        initView();
        initEvent();

        getFaultDetail();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getFaultOptions();
        //testOptions();
    }

    @Override
    protected void initView() {
        super.initView();
        setTopTitle("故障信息");
        setTopRight(R.drawable.send);
    }

    protected void initEvent() {
        upload_1.setOnClickListener(this);
        upload_2.setOnClickListener(this);
        findViewById(R.id.title_right).setOnClickListener(this);
        findViewById(R.id.fault_car_layout).setOnClickListener(this);
        findViewById(R.id.fault_level_layout).setOnClickListener(this);
        findViewById(R.id.fault_type_layout).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.fault_car_layout:
                chooseNumberDialog(1);
                break;
            case R.id.fault_level_layout:
                chooseNumberDialog(2);
                break;
            case R.id.fault_type_layout:
                chooseNumberDialog(3);
                break;
            case R.id.upload_1:
                if(View.VISIBLE == upload_2.getVisibility()) {
                    if("0".equals(mediaType)) {//查看图片
                        Intent intent = new Intent(mContext, PhotoViewActivity.class);
                        if(TextUtils.isEmpty(localMediaUrl)){
                            intent.putExtra("imagePath", NetUtil.getFullPath(mFaultDetail.getMediaUrl()));
                        }else{
                            intent.putExtra("imagePath", localMediaUrl);
                        }
                        startActivity(intent);
                    }else {//播放视频
                        Intent intent = new Intent(mContext, PlayVideoActivity.class);
                        if(TextUtils.isEmpty(localMediaUrl)){
                            intent.putExtra("videoPath", NetUtil.getFullPath(mFaultDetail.getMediaUrl()));
                        }else{
                            intent.putExtra("videoPath", localMediaUrl);
                        }
                        startActivity(intent);
                    }
                }else {
                    getPermissions();
                }
                break;
            case R.id.upload_2:
                getPermissions();
                break;
            case R.id.title_right:
                String title = fault_title.getText().toString();
                String car = fault_car.getText().toString();
                String location = fault_location.getText().toString();
                String level = fault_level.getText().toString();
                String type = fault_type.getText().toString();
                String detail = fault_detail.getText().toString();

                if (!check(title, car, location, level, type, detail)) {
                    return;
                }

                if(TextUtils.isEmpty(localMediaUrl)){
                    updateFault(mFaultDetail.getMediaType(), mFaultDetail.getMediaUrl());
                }else {
                    sendPicture(new UploadFileListener() {
                        @Override
                        public void uploadFileSuccess(String fileType, String fileUrl) {
                            updateFault(fileType, fileUrl);
                        }
                    });
                }
                break;
        }
    }

    private void getFaultDetail() {
        HttpLoader.getFaultDetail(faultId, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    hide();
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    hide();
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                mFaultDetail = ((FaultDetailModel) model).getData();
                setFaultData();
            }
        });
    }

    private void setFaultData() {
        FaultDetailModel.FaultDetail fault = mFaultDetail;
        fault_title.setText(fault.getTitle());
        fault_location.setText(fault.getAddress());
        fault_detail.setText(fault.getContent());

        VehicleId vehicleId = fault.getVehicleId();
        selectedCar.setId(vehicleId.getId());
        selectedCar.setParamName(vehicleId.getName());
        fault_car.setText(vehicleId.getName());

        Level level = fault.getLevelId();
        selectedLevel.setId(level.getId());
        selectedLevel.setParamName(level.getParamName());
        fault_level.setText(level.getParamName());

        Type type = fault.getTypeId();
        selectedType.setId(type.getId());
        selectedType.setParamName(type.getParamName());
        fault_type.setText(type.getParamName());

        mediaType = fault.getMediaType();//任务多媒体类型0照片1视频
        String mediaUrl = fault.getMediaUrl();
        if(!TextUtils.isEmpty(mediaUrl)){
            String existMediaUrl = NetUtil.getFullPath(mediaUrl);
            upload_2.setVisibility(View.VISIBLE);
            if("0".equals(mediaType)) {
                ImageUtil.bindImageView(upload_1, existMediaUrl, R.drawable.ic_default_photo);
                video_icon.setVisibility(View.INVISIBLE);
            }else{
                video_icon.setVisibility(View.VISIBLE);
                showVideoFirstFrame(2, existMediaUrl);
            }
        }
    }

    private void showVideoFirstFrame(int what, String path){
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = path;
        mHandler.sendMessage(msg);
    }

    private void updateFault(String mediaType, String uploadedMediaUrl) {
        String title = fault_title.getText().toString();
        //String car = fault_car.getText().toString();
        String location = fault_location.getText().toString();
        //String level = fault_level.getText().toString();
        //String type = fault_type.getText().toString();
        String detail = fault_detail.getText().toString();

        VehicleId vehicleIdEntity = new VehicleId();
        vehicleIdEntity.setId(selectedCar.getId());
        Level levelEntity = new Level();
        levelEntity.setId(selectedLevel.getId());
        Type typeEntity = new Type();
        typeEntity.setId(selectedType.getId());
        //Creator creatorEntity = new Creator();
        //creatorEntity.setId(UserPreferences.getInstance().getUserId());
        String time = TimeUtil.getCurDatetime("yyyy-MM-dd HH:mm:ss");

        showAlways("正在处理，请稍候...");
        HttpLoader.faultUpdate(faultId, title, vehicleIdEntity, location, levelEntity, typeEntity, detail,
                time, mediaType, uploadedMediaUrl, new HttpBase.IResponseListener() {
                    @Override
                    public void onResponse(BaseModel model) {
                        hide();
                        if (model == null) {
                            ToastUtil.showShort(R.string.please_check_network);
                            return;
                        }
                        if (!model.success()) {
                            ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                            return;
                        }

                        ToastUtil.showShort("修改成功！");
                        finish();
                    }
                });
    }
}
